//数据源管理
import React, { useState, useEffect }  from 'react';
import {Table, Row,Col, Modal, Button, Form, Input, message,Tree} from 'antd';
import {getResources, saveResource, removeResourceById, delUser} from "../api/Security";
import {saveDS} from "../api/metaDatasourceService";
import {ExclamationCircleOutlined} from "@ant-design/icons";



export  default  function Resource(props) {
    const [data, setData] = useState([]);

    const [itemId ,setItemId] = useState(-1);
    const [resourceCode ,setResourceCode] = useState("");
    const [resourceName ,setResourceName] = useState("");
    const [resourceUrl ,setResourceUrl] = useState("");
    const [resourceOrder ,setResourceOrder] = useState(-1);

//编辑状态
    const [modifyStatus ,setModifyStatus] = useState(0);  //0 查看  1 新增加  2 编辑   -1 刚刚删除一个节点

    const [flag,setFlag]=useState(0);

    const [form] = Form.useForm();

    useEffect(() => {
        getResources().then(
            (res) => {
                setData(res.data)
            },
            (error) => {
                console.log("get UserList failed!");
            }
        );
    }, [flag]);

    const  add=()=>{
        //
        if(itemId==undefined || itemId==null || itemId<0){
          message.info("请选择一个节点");
          return
        }
            setModifyStatus(1);
        form.setFieldsValue({
            "id":-100,
            "RESOURCECODE":"",
            "RESOURCENAME":"",
            "RESOURCEURL":"",
            "RESOURCEORDER":100
        })

    }

    const  edit=()=>{
        if(itemId==undefined || itemId==null || itemId<=0){
            message.info("请选择一个节点");
            return
        }
        setModifyStatus(2);
    }

    const  del=()=>{
        if(itemId==undefined || itemId==null || itemId<=0){
            message.info("请选择一个节点");
            return
        }
        const { confirm } = Modal;

        confirm({
            title: 'Do you Want to delete this items',
            icon: <ExclamationCircleOutlined />,
            content: '删除选中的条目',
            onOk() {
                removeResourceById(itemId).then(
                    (res) => {
                        if(res.code==200){
                            message.success("删除成功")
                            window.location.reload();
                        }else{
                            message.error(res.msg);
                        }
                    },
                    (error) => {
                       window.location.reload();
                        //this.componentDidMount();
                        message.success("保存失败")
                    }
                );
            },
            onCancel() {
                console.log('Cancel');

            },
        });
    }

    const ResourceTree = () => {
        const onSelect = (selectedKeys, info) => {
            console.log('selected', selectedKeys, info);
            //根据info 设置state相关值
            let _code=info.node.text
            let _id=info.node.id
            let _name=info.node.title;
            let _path=info.node.path;
            let _position=info.node.position;
            setItemId(_id);
            setResourceCode(_code);
            setResourceName(_name);
            setResourceUrl(_path);
            setResourceOrder(_position);
            form.setFieldsValue({
                "id":_id,
                "RESOURCECODE":_code,
                "RESOURCENAME":_name,
                "RESOURCEURL":_path,
                "RESOURCEORDER":_position
            })
        };

        // const onCheck = (checkedKeys, info) => {
        //     console.log('onCheck', checkedKeys, info);
        // };

        return (
            <Tree
                onSelect={onSelect}
                // onCheck={onCheck}
                treeData={data}
            />
        );
    };


    const ResourceItem = () => {
        const onFinish = (values) => {
            console.log('Success:', values);
            if(values.id!=-100){
                message.info("不是新增状态，无法保存")
                return
            }

            let _obj={
                "description": values.RESOURCENAME,
                "icon": "",
                "id":values.id,
                "menutype": 0,
                "parentId": itemId,
                "position": values.RESOURCEORDER,
                "resourceCode": values.RESOURCECODE,
                "resourceIcon": "",
                "resourceName": values.RESOURCENAME,
                "resourceOrder":  values.RESOURCEORDER,
                "resourceType": 0,
                "resourceUrl": values.RESOURCEURL,
                "stateFlag": ""
            }

            console.log('Success:', _obj);
            saveResource(_obj).then(
                (res) => {
                    //把后端数据组织到前端
                    // this.refreshForm(this.state.selectedFolderId);
                   // setFlag(flag+1);
                    message.success("保存成功")
                    window.location.reload();
                    // 刷缓存;
                    //setVisible(false);
                },
                (error) => {
                    window.location.reload();
                    //this.componentDidMount();
                    message.success("保存失败")
                }
            );
        };

        const onFinishFailed = (errorInfo) => {
            console.log('Failed:', errorInfo);
        };

        const onReset = () => {
            form.resetFields();
        };

        return (
            <Form
                name="basic"
                form={form}
                labelCol={{
                    span: 8,
                }}
                wrapperCol={{
                    span: 16,
                }}
                initialValues={{
                    id:itemId,
                    RESOURCECODE:resourceCode,
                    //RESOURCECODE:999,
                    RESOURCENAME:resourceName,
                    // RESOURCENAME:"ddd",
                    resourceUrl:resourceUrl,
                    resourceorder:resourceOrder

                }}
                onFinish={onFinish}
                onFinishFailed={onFinishFailed}
            >

                <Form.Item
                    label=""
                    name="id"
                    hidden={true}
                >
                    <Input />
                </Form.Item>

                <Form.Item
                    label="RESOURCECODE"
                    name="RESOURCECODE"
                    rules={[
                        {
                            required: true,
                            message: 'Please input the resource code!',
                        },
                    ]}
                >
                    <Input />
                </Form.Item>


                <Form.Item
                    label="RESOURCENAME"
                    name="RESOURCENAME"
                    rules={[
                        {
                            required: true,
                            message: 'Please input the resource name!',
                        },
                    ]}
                >
                    <Input />
                </Form.Item>

                <Form.Item
                    label="RESOURCEURL"
                    name="RESOURCEURL"
                    rules={[
                        {
                            required: true,
                            message: 'Please input resource url!',
                        },
                    ]}
                >
                    <Input />
                </Form.Item>

                <Form.Item
                    label="RESOURCEORDER"
                    name="RESOURCEORDER"
                    rules={[
                        {
                            required: true,
                            message: 'Please input the resource order!',
                        },
                    ]}
                >

                    <Input />
                </Form.Item>


                <Form.Item
                    wrapperCol={{
                        offset: 8,
                        span: 16,
                    }}
                >
                    <Button type="primary" htmlType="submit">
                        Submit
                    </Button>

                    {/*<Button htmlType="button" onClick={onReset}>*/}
                        {/*Reset*/}
                    {/*</Button>*/}

                </Form.Item>
            </Form>
        );
    }




    return (
        <>
            <Row>
                <Button onClick={add}>增加</Button>
                {/*<Button onClick={edit}>修改</Button>*/}
                <Button onClick={del}>删除</Button>
            </Row>

            <Row>
                <Col span={8}>
                    {ResourceTree()}
                </Col>
                <Col span={16}>
                    {ResourceItem()}
                </Col>
            </Row>

        </>


    );





}






